<?php
declare(strict_types=1);
namespace app\shop\controller;

use app\shop\logic\VoteLogic;
use app\shop\model\vote\log;
use app\shop\model\vote\vote;
use think\response\Json;
use app\shop\exception\FailException;
use app\shop\exception\ParamsErrorException;

class VoteController extends BaseController
{
    protected array $noNeedLogin = ['getPageList','getTypeList','detail'];
    public function __construct()
    {
        parent::__construct();

        $this->logic = new VoteLogic();
    }

    /**
     * 投票列表
     * @return Json
     * @throws \app\shop\exception\ParamsErrorException
     */
    public function getPageList(): Json
    {
        $params = $this->postInput(true);

        $this->validateData($params, 'list');

        $result = $this->logic->VoteList($params);

        return $this->success($result);
    }

    /**
     * 投票详情
     * @return Json
     * @throws \app\shop\exception\FailException
     * @throws \app\shop\exception\ParamsErrorException
     */
    public function detail(): Json
    {
        $params = $this->postInput(true);

        $this->validateData($params, 'detail');

        $result = $this->logic->detail($params);

        return $this->success($result);
    }

    /**
     * 分类列表
     * @return Json
     */
    public function getTypeList(): Json
    {
        $result = $this->logic->typeList();

        return $this->success($result);
    }

    /**
     * 去投票
     * @return \Psr\Http\Message\StreamInterface|Json
     */
    public function vote(){
        $params = $this->postInput(true);
        if(!$params['id']){
            return $this->error('缺少id');
        }
        $logModel = new log();
        if($logModel->where('vote_id',$params['id'])->where('user_id',$params['user_id'])->find()){
            throw new ParamsErrorException('已投票');
        }else{
            $logModel->insert([
                'vote_id' => $params['id'],
                'user_id' => $params['user_id'],
            ]);
        }
        $model = new vote();
        $res = $model->where('id',$params['id'])->setInc('num',1);
        if(!$res){
            throw new ParamsErrorException('投票失败');
        }
        return $this->success('成功');
    }



}